import requests
import time
import openpyxl
from openpyxl.styles import Font

# 替换为你的码云 API Token
GITEE_ACCESS_TOKEN = 'your_gitee_access_token'

# 码云 API 基础 URL
GITEE_API_BASE_URL = 'https://gitee.com/api/v5'

# 速率限制：每秒最多 10 次请求（码云 API 限制）
RATE_LIMIT = 10  # 每秒最多请求次数
REQUEST_INTERVAL = 1 / RATE_LIMIT  # 每次请求的间隔时间

def get_repo_collaborators(repo_full_name):
    """
    获取仓库的协作者信息
    :param repo_full_name: 仓库全名（如：username/repo_name）
    :return: 协作者列表
    """
    url = f'{GITEE_API_BASE_URL}/repos/{repo_full_name}/collaborators'
    headers = {
        'Authorization': f'token {GITEE_ACCESS_TOKEN}'
    }
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f'Error: {response.status_code} - {response.text}')
        return None

def get_user_email(username):
    """
    获取用户的邮箱（如果公开）
    :param username: 用户名
    :return: 邮箱地址
    """
    url = f'{GITEE_API_BASE_URL}/users/{username}'
    headers = {
        'Authorization': f'token {GITEE_ACCESS_TOKEN}'
    }
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        user_info = response.json()
        return user_info.get('email', 'N/A')  # 如果邮箱未公开，返回 'N/A'
    else:
        print(f'Error: {response.status_code} - {response.text}')
        return 'N/A'

def read_repo_list(file_path):
    """
    从文件中读取仓库列表
    :param file_path: 文件路径
    :return: 仓库列表
    """
    with open(file_path, 'r', encoding='utf-8') as file:
        repo_list = [line.strip() for line in file if line.strip()]
    return repo_list

def save_to_excel(data, output_file):
    """
    将数据保存到 Excel 文件
    :param data: 数据列表，每个元素是一个字典
    :param output_file: 输出文件路径
    """
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title = "Repository Admins"

    # 设置表头
    headers = ["Repository", "Admin Username", "Admin Email"]
    for col_num, header in enumerate(headers, 1):
        sheet.cell(row=1, column=col_num, value=header).font = Font(bold=True)

    # 填充数据
    for row_num, repo_info in enumerate(data, 2):
        sheet.cell(row=row_num, column=1, value=repo_info['repo'])
        sheet.cell(row=row_num, column=2, value=repo_info['admin_username'])
        sheet.cell(row=row_num, column=3, value=repo_info['admin_email'])

    # 保存文件
    workbook.save(output_file)
    print(f"数据已保存到 {output_file}")

def main():
    # 输入文件路径
    input_file = 'sig-1.txt'
    # 输出文件路径
    output_file = 'repository_admins.xlsx'

    # 读取仓库列表
    repo_list = read_repo_list(input_file)
    print(f"共读取到 {len(repo_list)} 个仓库")

    # 查询仓库管理员信息
    results = []
    for repo in repo_list:
        print(f"正在查询仓库: {repo}")
        collaborators = get_repo_collaborators(repo)
        if collaborators:
            # 筛选出管理员
            admins = [collab for collab in collaborators if collab.get('permissions', {}).get('admin')]
            for admin in admins:
                admin_username = admin.get('login', 'N/A')
                admin_email = get_user_email(admin_username)  # 获取邮箱
                results.append({
                    'repo': repo,
                    'admin_username': admin_username,
                    'admin_email': admin_email
                })
        else:
            print(f"仓库 {repo} 查询失败")

        # 速率限制：等待一段时间再发送下一个请求
        time.sleep(REQUEST_INTERVAL)

    # 将结果保存到 Excel 文件
    save_to_excel(results, output_file)

if __name__ == '__main__':
    main()